<?php
namespace service;

use think\Cache;
use think\Log;

class TencentMapService
{
	const KEY     = '7WCBZ-UONL2-U75UX-CZ5BK-5IWF3-ZSFM3';
	const SK      = 'RFtZXNGoF6B82f7NreKlcIhwQbB0Qn';
	protected static $baseUrl = 'https://apis.map.qq.com';

	/**
	 * 地址解析【地址转经纬度】
	 * @Author   FW
	 * @DateTime 2021-09-08
	 * @Email    123763712@qq.com
	 * @see https://lbs.qq.com/service/webService/webServiceGuide/webServiceGeocoder
	 * @param    [type]           $address [description]
	 * @return   [type]                    [description]
	 */
	public static function geocoder ( $address , $callback = null )
	{
		$path = '/ws/geocoder/v1';
		$query['address'] = $address;
		$query['key']     = static::KEY;
		$query['sig']     = static::getSign($path , $query);
		$result  = self::curlRequest( static::$baseUrl . $path . '?' . http_build_query($query) );
		$return  = [
			'lng' => 0,
			'lat' => 0
		];
		if ( isset($result['status']) && $result['status'] == 0 ) {
			if ( isset($result['result']) ) {
				$return['lng'] = $result['result']['location']['lng'] ?? 0;
				$return['lat'] = $result['result']['location']['lat'] ?? 0;
				if ( $return['lng'] && $return['lat'] ) {
					if ( is_callable($callback) ) {
						return $callback($return);
					}
				}
			}
		}
		return $return;
	}

	/**
	 * 签名计算
	 * @Author   FW
	 * @DateTime 2021-09-08
	 * @Email    123763712@qq.com
	 * @param    [type]           $path   [description]
	 * @param    array            $params [description]
	 * @return   [type]                   [description]
	 */
	public static function getSign ( $path , array $params)
	{
		ksort($params);
		$pstring = [];
		foreach ( $params as $key => $val ) {
			$pstring[] = sprintf("%s=%s" , $key, $val);
		}
		return md5($path . '?' . join('&',$pstring) . static::SK);
	}

	/**
	 * @Description: curl请求
	 * @Author: FW
	 * @param $url
	 * @param null $data
	 * @param string $method
	 * @param array $header
	 * @param bool $https
	 * @param int $timeout
	 * @return mixed
	 */
	public static function curlRequest($url, $data=null, $method='get', $header = array("content-type: application/json"), $https=true, $timeout = 5 , $josn2Arr = true){
	    $method = strtoupper($method);
	    $ch = curl_init();//初始化
	    curl_setopt($ch, CURLOPT_URL, $url);//访问的URL
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
	    if($https){
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
	        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
	    }

	    if ($method != "GET") {
	        if($method == 'POST'){
	            curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
	            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));//请求数据
	        }
	        if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
	            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
	        }

			Log::info('curl send data:' .  json_encode($data));
	    }
	    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
	    //curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息


	    $result = curl_exec($ch);//执行请求
	    curl_close($ch);//关闭curl，释放资源

	    if ( $josn2Arr && is_string($result) ) {
	    	$result = json_decode($result,true);

	    	if ( json_last_error() > 0 ) {
	    		return [];
	    	}
	    }
	    Log::info('curl responde data:' .  json_encode($result));
	    return $result;
	}
}